package com.zprmb.udzt;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.growingio.android.sdk.collection.GrowingIO;
import com.zprmb.udzt.activity.XianFengChongZhiActivity;
import com.zprmb.udzt.gesture.GestureEditActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.rsa.Base64;
import com.zprmb.udzt.rsa.ConfigureEncryptAndDecrypt;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.MySharePreferenceUtil;
import com.zprmb.udzt.util.PermissionUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.WaveHelper;

import org.json.JSONObject;

import java.lang.reflect.Method;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Date;

import javax.crypto.Cipher;

import static com.taobao.accs.ACCSManager.mContext;
import static com.zprmb.udzt.R.drawable.close;

public class V6LoginActivity extends BaseActivity implements OnClickListener {
    private WaveHelper helper;
    private TextView btn_register;
    private ImageView img_close;
    private ImageView img_clear;
    private EditText user_phone_num, user_password;
    private Button btn_login;
    private TextView enterprise_tel;
    private ImageView pass, img_clear_user;
    private TextView tv_messagelogin;
    private RelativeLayout rl_back;
    private LinearLayout li_opera;
    private TextView tv_forget;
    private TextView tv_comment;
    private PopupWindow popWindow;
    Dialog dialog;
    private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCb9I0Uohf2nTP3zyOk7q+Fuo7szbp0XYFzW0ik52DGnLH6TGooO1DIjbgQ8GgsW6YH0xby/R4eWc1U4U64jSGKiIcYRmUQvSWuPiKk8qT9g6ukMcMmNg3nWH2KOWPyYADOPL3w1maVB6+SZ/G8c9pTqjQlpLmTFM9sFy09v2+RGQIDAQAB";

    public static String token = "";

    public void checkUpdatePermission2() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                ) {
            requestUpdatePermission2();
        } else {

        }
    }

    int sum;
    private AlertDialog alertDialog1;
    private boolean isPermissionDialogShow = false;

    /**
     * 解释权限的dialog
     */
    private void showExplainDialog() {
        alertDialog1 = new AlertDialog.Builder(mContext)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissionState = true;
                        PermissionUtils.toAppSetting(mContext);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .create();

        if (!alertDialog1.isShowing()) {

            alertDialog1
                    .show();
            isPermissionDialogShow = true;
        }


        alertDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                isPermissionDialogShow = false;
            }
        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();

        if (sum < 0) {
            checkUpdatePermission();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d("SplashActivity", "--> onRequestPermissionsResult:permissions = " + Arrays.toString(permissions));
        Log.d("SplashActivity", "--> onRequestPermissionsResult:grantResults = " + Arrays.toString(grantResults));
        sum = 0;
        for (int grant : grantResults) {
            sum += grant;
        }
        if (sum < 0) {
//            showExplainDialog();
            Toast.makeText(V6LoginActivity.this, "您未对该设备授权,请对该设备授权", Toast.LENGTH_SHORT).show();
            PermissionUtils.toAppSetting(mContext);
        } else {

        }



    }

    public void requestUpdatePermission2() {
        String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE};

        ActivityCompat.requestPermissions(this, permissions, 1);

    }

    String userMobile;
    TextView tv_minsheng;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6login_activity);
        Log.e("login","V6LoginActivity");

        BbtApplication.getInstance().addActvity(this);
        setMiuiStatusBarDarkMode(this, true);
        setStatusBarIconDark(true);
        setImmersionStatus();
        checkUpdatePermission2();
        userMobile = (String) MySharePreferenceUtil.get(V6LoginActivity.this, "userMobile", "");

        BbtApplication.getInstance().addActvity(this);
        setTitle("登录", this);

        tv_comment = (TextView) findViewById(R.id.tv_comment);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        li_opera = (LinearLayout) findViewById(R.id.li_opera);
        img_clear = (ImageView) findViewById(R.id.img_clear);
        pass = (ImageView) findViewById(R.id.img_pass);
        btn_login = (Button) findViewById(R.id.btn_login);

        tv_minsheng= (TextView) findViewById(R.id.tv_minsheng);
        tv_minsheng.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                startActivity(new Intent(V6LoginActivity.this,XianFengChongZhiActivity.class));
            }
        });
        tv_messagelogin = (TextView) findViewById(R.id.tv_messagelogin);
        tv_forget = (TextView) findViewById(R.id.tv_forget);
        enterprise_tel = (TextView) findViewById(R.id.enterprise_tel);
//		wv.setWavebehindcolor(Color.parseColor("#4c80C4FE"));
        user_phone_num = (EditText) findViewById(R.id.user_phone_num);
        user_password = (EditText) findViewById(R.id.user_password);
        btn_register = (TextView) findViewById(R.id.btn_register);
        img_close = (ImageView) findViewById(R.id.img_back);
        img_close.setVisibility(View.GONE);
        img_clear_user = (ImageView) findViewById(R.id.img_clear_user);
        img_clear_user.setOnClickListener(this);
        rl_back.setOnClickListener(this);
        rl_back.setVisibility(View.GONE);
        img_clear.setOnClickListener(this);
        img_close.setOnClickListener(this);
        enterprise_tel.setOnClickListener(this);
        tv_messagelogin.setOnClickListener(this);
        tv_forget.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        zhiwen = (String) MySharePreferenceUtil.get(V6LoginActivity.this, "zhiwendenglu", "");
        pass.setOnClickListener(this);
//		wv.setImageBitmap(BitmapUtils.readBitMap(this, R.drawable.v6_login_bg));
        user_phone_num.setText(getShare().getString("mobile", ""));
//		ToastUtil.showCenterToast(this, getDeviceType());
        if (user_phone_num.getText().toString().equals("")) {
            img_clear_user.setVisibility(View.GONE);
        } else {
            img_clear_user.setVisibility(View.VISIBLE);
        }
        user_phone_num.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if (user_phone_num.getText().toString().equals("")) {
                    img_clear_user.setVisibility(View.GONE);
                } else {
                    img_clear_user.setVisibility(View.VISIBLE);
                }
            }
        });
        user_password.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

                if (user_password.getText().toString().equals("")) {
                    li_opera.setVisibility(View.GONE);
                } else {
                    li_opera.setVisibility(View.VISIBLE);
                }

            }
        });
    }

    private void changeCommentStatus(int status, String comment) {
        if (status == 1) {
            if (tv_comment.getVisibility() == View.GONE) {
                tv_comment.setVisibility(View.VISIBLE);
                tv_comment.setText(comment);
            }
        } else {
            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
    }

    private long mLastBackTime = 0;
    private long TIME_DIFF = 2 * 1000;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long now = new Date().getTime();
            if (now - mLastBackTime < TIME_DIFF) {

                BbtApplication.getInstance().exit();
                android.os.Process.killProcess(android.os.Process.myPid());
                //BbtApplication.getInstance().exit();

                finish();
                return super.onKeyDown(keyCode, event);
            } else {
                mLastBackTime = now;
                Toast.makeText(this, "再按一次退出优点智投", 2000).show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (tv_comment != null) {

            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (tv_comment.getVisibility() == View.VISIBLE) {
            tv_comment.setVisibility(View.GONE);
        }
    }

    String string = "";
    String zhiwen;

    private void V6login() {
        final String gesture = (String) MySharePreferenceUtil.get(V6LoginActivity.this, "gesture", "");

        AjaxParams params = new AjaxParams();
        params.put("loginType", "PWD");
        params.put("loginName", user_phone_num.getText().toString().trim());
        params.put("password", user_password.getText().toString().trim());
        VolleryUtil volleryUtil = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("login", jsonObject.toString());
                if (jsonObject.optInt("success") == 1) {
                    token = jsonObject.optString("token");

                    SharedPreferences.Editor editor2 = getSharedPreferences("config", MODE_PRIVATE).edit();
                    editor2.putString("isTop", "2");
                    editor2.putInt("top", 1);
                    editor2.commit();
                    JSONObject json1 = jsonObject.optJSONObject("data");
                    string = jsonObject.optString("token");
                    token = json1.optString("token");
                    Log.e("token",token);
                    MySharePreferenceUtil.put(V6LoginActivity.this, "mytoken", token);
                    Editor editor = getShare().edit();
                    editor.putString(
                            "token",
                            json1.optString(
                                    "token"));
                    editor.putString(
                            "userId",
                            json1.optString(
                                    "userId"));
                    editor.putString(
                            "photoUrl",
                            json1.optString(
                                    "photoUrl"));
                    editor.putString(
                            "mobile",
                            json1.optString(
                                    "mobile"));
                    editor.putString(
                            "usercode",
                            json1.optString(
                                    "userCode"));
                    try {
                        editor.putString(
                                "password",
                                encrypt(user_password.getText().toString().trim(), publicKey));
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    editor.putString("loginName", getIntent().getStringExtra("phone"));
                    editor.commit();
                    GrowingIO.getInstance().setCS1("user_id", getUserId());

//                    ToastUtil.showCenterToast(V6LoginActivity.this,userMobile);

                    if (TextUtils.isEmpty(userMobile)) {
                        Intent intent = new Intent(V6LoginActivity.this, GestureEditActivity.class);//MainActivity
                        intent.putExtra("from", "login");
                        intent.putExtra("towhere", "main");
                        intent.putExtra("web", getIntent().getIntExtra("web", 0));
                        intent.putExtra("product", getIntent().getIntExtra("product", 0));
                        intent.putExtra("token", string);

                        startActivity(intent);
                        V6LoginActivity.this.finish();
                        return;
                    } else if (!userMobile.equals(user_phone_num.getText().toString())) {

                        Intent intent = new Intent(V6LoginActivity.this, GestureEditActivity.class);//MainActivity
                        intent.putExtra("from", "login");
                        intent.putExtra("towhere", "main");
                        intent.putExtra("web", getIntent().getIntExtra("web", 0));
                        intent.putExtra("product", getIntent().getIntExtra("product", 0));
                        intent.putExtra("token", string);
                        startActivity(intent);
                        V6LoginActivity.this.finish();
                        return;
                    } else if (gesture.equals(0) && TextUtils.isEmpty(userMobile)) {
                        Intent intent = new Intent(V6LoginActivity.this, GestureEditActivity.class);//MainActivity
                        intent.putExtra("from", "login");
                        intent.putExtra("towhere", "main");
                        intent.putExtra("web", getIntent().getIntExtra("web", 0));
                        intent.putExtra("product", getIntent().getIntExtra("product", 0));
                        intent.putExtra("token", string);
                        startActivity(intent);
                        V6LoginActivity.this.finish();
                        return;
                    }else if (gesture.equals("1") || zhiwen.equals("1")){
                        Intent intent = new Intent(V6LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        V6LoginActivity.this.finish();
                        MySharePreferenceUtil.put(V6LoginActivity.this, "newintentflag", "1");
                    }

                    else {
                        int close = getIntent().getIntExtra("close", 0);

                        if (close == 1) {

                            if (getIntent().getIntExtra("web", 0) == 1) {
                                if (getIntent().getIntExtra("assets", 0) == 1) {
                                    Intent intent = new Intent();
//							intent.putExtra("resultcode", 1);

                                    setResult(2, intent);
                                    finish();
                                    return;
                                }
                                Intent intent = new Intent();
                                intent.putExtra("resultcode", 1);
                                setResult(1, intent);
                                Log.e("web", "web");
                                finish();

                            } else {
                                Intent intent = new Intent();
                                setResult(1, intent);

                                V6LoginActivity.this.finish();
                            }
                            return;

                        } else {
                            Intent intent = new Intent(V6LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            V6LoginActivity.this.finish();
                            MySharePreferenceUtil.put(V6LoginActivity.this, "newintentflag", "1");
                        }
                    }



                } else {
                    btn_login.setBackgroundResource(R.drawable.v6button);
                    btn_login.setText("登录");
                    btn_login.setEnabled(true);
                    if (jsonObject.optString("comment").contains("锁")) {

                        showUpVersionDialog(jsonObject.optString("comment"));

                    } else {
                        changeCommentStatus(1, jsonObject.optString("comment"));

                    }

                }
            }

            @Override
            public void onError() {

            }
        };

        volleryUtil.setRequestMethod(1);
        volleryUtil.setShow(true);
        volleryUtil.setHeaders("appVersion", getAppVersion());
        volleryUtil.setHeaders("client", "android");

        volleryUtil.setHeaders("deviceToken", getdevice_token());
//
//
        volleryUtil.setHeaders("deviceId", getdeviceId());
        volleryUtil.setHeaders("mobileType", getDeviceType());



        volleryUtil.execute(V6LoginActivity.this, Constant.URL + "/api/v6/login/app?", params.toString());

    }


    private void showPopupWindow(View parent, String message) {
        if (popWindow == null) {

            View view = LayoutInflater.from(this).inflate(R.layout.dialog_01, null);
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop(view, message);
        }
        //设置动画效果
        popWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop(View view, String message) {


    }

    private void showUpVersionDialog(String content) {
        dialog = new Dialog(V6LoginActivity.this, R.style.alert_dialog);
        dialog.setCancelable(false);

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(
                R.color.float_transparent)));
        window.setGravity(Gravity.CENTER);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        window.setContentView(R.layout.dialog_01);

        dialog.show();
        TextView tv01 = (TextView) window.findViewById(R.id.dl_tv_01);//联系客服
        TextView text_status = (TextView) window.findViewById(R.id.text_status);

        TextView dl_tv_02 = (TextView) window.findViewById(R.id.dl_tv_02);

        if (content.indexOf("，") != -1) {

            text_status.setText(content.substring(content.indexOf("，") + 1, content.length()));
        }
        tv01.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {


//                popWindow.dismiss();
                if (dialog != null) {
                    dialog.dismiss();
                }
                BaseHelper.showDialog2(V6LoginActivity.this, "拨号", getResources().getString(R.string.tel), 1);
            }
        });
        dl_tv_02.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub

        return super.onTouchEvent(event);
    }

    private void setStatusBarIconDark(boolean dark) {
        try {
            Object win = getWindow();
            Class<?> cls = win.getClass();
            Method method = cls.getDeclaredMethod("setStatusBarIconDark", boolean.class);
            method.invoke(win, dark);
        } catch (Exception e) {
            Log.e("ff", "statusBarIconDark,e=" + e);
        }
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public String encrypt(String source, String publicKey)
            throws Exception {
        Key key = getPublicKey(publicKey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return new String(Base64.encodeBase64(b1),
                ConfigureEncryptAndDecrypt.CHAR_ENCODING);
    }

    public static PublicKey getPublicKey(String key) throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                Base64.decodeBase64(key.getBytes()));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    private boolean requestPermissionState = false;
//    private AlertDialog alertDialog1;

    /**
     * 解释权限的dialog
     */
/*    private void showExplainDialog() {
        alertDialog1 = new AlertDialog.Builder(mContext)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        requestPermissionState = true;
                        PermissionUtils.toAppSetting(mContext);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .create();

        if (!alertDialog1.isShowing()) {

            alertDialog1
                    .show();
        }


        alertDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });

    }*/
    @Override
    protected void onResume() {
        super.onResume();

    }


    // 普通申请一个权限
    private void checkPermission() {


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(0);
        }

    }

    private final int REQUEST_CODE_CAMERA = 1, REQUEST_CODE_PERMISSIONS = 2;
    private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.USE_FINGERPRINT};
    private AlertDialog alertDialog;

    private void requestPermission(int permission) {


        ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);

//        switch (permission) {
//            case PERMISSION_READ_PHONE_STATE:
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, STATE_READ_PHONE_STATE);
//                break;
//            case PERMISSION_CALL_PHONE:
//
//                break;
//            case PERMISSION_EXTERNAL_STORAGE:
//
//                break;
//            case PERMISSION_USE_FINGERPRINT:
//
//                break;
//        }

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = null;
        switch (v.getId()) {

            case R.id.btn_register:
                intent = new Intent(V6LoginActivity.this, V6RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_login:
//                checkPermission();
                if (user_password.getText().toString().equals("")) {
                    Toast.makeText(V6LoginActivity.this, "登录密码不能为空", 0).show();
                    return;
                }

                btn_login.setBackgroundResource(R.drawable.btn_unclick);
                btn_login.setText("登录中...");
                btn_login.setEnabled(false);
                V6login();
                break;
            case R.id.img_back:
                if (getIntent().getIntExtra("web", 0) == 1) {
                /*    intent = new Intent(V6LoginActivity.this, MainActivity.class);
                    startActivity(intent);*/
                    finish();
                } else {

                    finish();
                }
                break;
            case R.id.rl_back:
                if (getIntent().getIntExtra("web", 0) == 1) {
                   /* intent = new Intent(V6LoginActivity.this, MainActivity.class);
                    startActivity(intent);*/
                    finish();
                } else {

                    finish();
                }
                break;
            case R.id.img_pass:
                if (user_password.getTransformationMethod().equals(PasswordTransformationMethod
                        .getInstance())) {
                    user_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan1);
                } else {
                    user_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    pass.setBackgroundResource(R.drawable.yan2);
                }
                break;
            case R.id.tv_messagelogin:
                intent = new Intent(V6LoginActivity.this, Message_Login.class);
                if (user_phone_num.getText().toString().equals("")) {
                    intent.putExtra("user_phone", "");
                } else {
                    intent.putExtra("user_phone", user_phone_num.getText().toString());
                }

                startActivity(intent);
//                finish();
                break;
            case R.id.tv_forget:
                intent = new Intent(V6LoginActivity.this, ForgetPwd.class);
                intent.putExtra("mobile", user_phone_num.getText().toString().trim());
                startActivity(intent);
                break;
            case R.id.img_clear:
                user_password.setText("");
                break;
            case R.id.img_clear_user:
                user_phone_num.setText("");
                break;
            case R.id.enterprise_tel:
                BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
                break;
        }
    }
}
